package edu.unlv.cs.ladders.services;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import org.joda.time.DateMidnight;
import org.joda.time.Period;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import edu.unlv.cs.ladders.entities.Event;
import edu.unlv.cs.ladders.entities.Score;
import edu.unlv.cs.ladders.entities.Tournament;

@RooJavaBean
@Service
public class CleanupAgentImpl implements CleanupAgent {
	private int daysAfterEvent = 7;
	private boolean challengerWinsOnTie = true;
	private EventService eventService;
	
	@Scheduled(cron="${schedule.close_tournaments_past_end_date}")
	@SuppressWarnings("unchecked")
	public void closeTournamentsPastEndDate() {
		List<Tournament> shouldBeClosed = (List<Tournament>)Tournament.findTournamentsByClosedAndEndDateLessThan(false, Calendar.getInstance()).getResultList();
		for(Tournament tournament : shouldBeClosed){
			tournament.setClosed(true);
			tournament.merge();
		}
	}

	@Scheduled(cron="${schedule.set_winner_of_event}")
	@SuppressWarnings("unchecked")
	public void setWinnerOfEvent() {
		Locale locale = Locale.US;
		Period periodToCleanupDate = Period.days(daysAfterEvent);
		DateMidnight today = new DateMidnight();
		DateMidnight cleanupDate = today.minus(periodToCleanupDate);
		List<Event> events = (List<Event>)Event.findEventsByDateOfEventBetween(cleanupDate.toCalendar(locale), cleanupDate.plus(Period.days(1)).toCalendar(locale)).getResultList();
		for(Event event:events){
			Score challengerScore = event.getChallengerScore();
			Score defenderScore = event.getDefenderScore();
			if(challengerScore.getScore()==defenderScore.getScore() &&
					   this.challengerWinsOnTie){
				this.getEventService().setWinner(event, 1, 0);
			}
		}
	}
	@Autowired
	public void setEventService(EventService eventService){
		this.eventService = eventService;
	}
}
